<template>
    <span v-if="isTable" class="overlay-layer" @dblclick="handleDblClick" @mouseenter="showTooltip"
        @mouseleave="hideTooltip">
        <el-input v-model="displayValue" :resize="'none'" autosize :maxlength="maxLength" class="areaInputStyle"
            type="textarea">
        </el-input>
    </span>
    <span v-else class="overlay-layer" @dblclick="handleDblClick" @mouseenter="showTooltip" @mouseleave="hideTooltip">
        <CrossRowInput v-model:value="displayValue" :line-config="rowConfig"></CrossRowInput>
    </span>
    <div id="tooltip" class="tooltip">
        单击输入，双击选择。
    </div>
    <!-- 选择单位对话框 -->
    <el-dialog v-model="showModal" :close-on-click-modal="false" width="1300px" align-center text-align: title="选择单位"
        :before-close="cleanModal">
        <div>
            <div><img src="../../assets/logo.png"
                    style="width: 40px;height:40px;margin-left: 20px;vertical-align: middle;" />
                <span style="font-size: 5mm;">{{ popTitleName }}</span>
            </div>
            <div style="margin:5px 10px;">
                <el-input v-model="search" placeholder="请输入单位名称、地址、营业执照号" style="width: 250px;margin-right: 5px"
                    clearable />
                <el-button type="primary" style="margin-left: 5px" @click="getTableData">搜索</el-button>
            </div>
            <hr class="yanse" border>
            <div class="privyInfoTable">
                <el-table :data="tableData" border stripe style="width: 100%" @row-click="selectUnit">
                    <el-table-column prop="companyName" label="单位名称" width="220" align="center" />
                    <el-table-column prop="companyAddress" label="地址" width="220" align="center" />
                    <el-table-column prop="companyLicense" label="信用代码或营业执照号" width="200" align="center" />
                    <el-table-column prop="legalPerson" label="法定代表人" width="200" align="center" />
                    <el-table-column prop="legalPersonPosition" label="法定代表人职务" width="200" align="center" />
                    <el-table-column prop="legalPersonPhone" label="法定代表人联系方式" width="200" align="center" />
                </el-table>
                <div class="footer">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script>
/**
 * 单位选择器组件（返回数组）
 * @description 用于选择单位信息并显示在输入框中（用于父组件多处位置需要组件返回数据）
 * @param {string} modelValue 双向绑定的单位值
 * @param {String} returnFields 返回模版 'A': '公司名称','B': '信用代码','C': '法人名称','D': '法人职务','E': '公司地址','F': '企业类型','G': '经营范围','H': '联系电话',
 * @param {Array} returnArrayTemplate 返回绑定的数据参数和数据格式模版
 * @param {Object} rowConfig 输入框的多行显示配置，包含每行字符数和行数
 * @param {Boolean} isSelected 用于配合控制文书（单位）删除线的功能（false表示手动输入，true表示通过组件选择）
 * @param {Boolean} isTable 用于判断是否在表格文书中使用
 * @param {Number} maxLength 表格文书中的输入框限制最大值
 */
import request from '@/utils/request'
import { popTitleName } from "../../utils/publicName.js"
import CrossRowInput from "@/views/template/CrossRowInput";

export default {
    components: {
        CrossRowInput
    },
    name: "PrivyInfoSelect",
    props: {
        modelValue: String,
        returnFields: {
            type: String,
            default: 'A'
        },
        returnArrayTemplate: {
            type: Array,
            default: () => []
        },
        rowConfig: {
            type: Object,
            default: () => ({
                firstLine: { chars: 28 * 2 },
                middleLines: { count: 0, chars: 32 * 2 },
                lastLine: { chars: 0 * 2 }
            })
        },
        // 用于标识值是否通过选择改变
        isSelected: {
            type: Boolean,
            default: false
        },
        // 用于判断是否在表格文书中使用
        isTable: {
            type: Boolean,
            default: false
        },
        // 表格文书中的输入框限制最大值
        maxLength: {
            type: Number,
            default: 10
        }

    },
    emits: ['update:modelValue', 'select', 'click', 'update:isSelected'],
    data() {
        return {
            popTitleName: popTitleName,
            displayValue: this.modelValue,
            showModal: false,
            search: '',
            typeId: '',
            options: [],
            tableData: [],
            total: 0,
            pageNum: 1,
            pageSize: 5,
            internalIsSelected: false,  // 内部状态标识是否是选择操作
            replaceDict: {
                'A': 'companyName',
                'B': 'companyLicense',
                'C': 'legalPerson',
                'D': 'legalPersonPosition',
                'E': 'companyAddress',
                'F': 'typeName',
                'G': 'businessNature',
                'H': 'legalPersonPhone',
            },
        }
    },
    watch: {
        modelValue(newVal) {
            this.displayValue = newVal;
        },
        displayValue(newVal) {
            if (newVal !== this.modelValue) {
                this.$emit('update:isSelected', this.internalIsSelected);
            }
            // 重置内部标识，下次改变默认为非选择操作
            this.internalIsSelected = false;

            this.$emit('update:modelValue', newVal);
            // 当值改变时，将内部标识同步到父组件
        }
    },
    mounted() {
        this.getTableData();;
    },
    methods: {
        handleDblClick() {
            this.showModal = true; // 显示选择器
        },
        selectUnit(unit) {
            let displayValue = this.returnFields;

            // 根据returnFields配置返回值
            let returnDataArray = []
            // 从替换字典中提取所有键，用|连接成字符串
            const keys = Object.keys(this.replaceDict).join('|');

            // 创建正则表达式，全局匹配所有替换键
            const regex = new RegExp(`([${keys}])`, 'g');
            displayValue = displayValue.replace(regex, (match) => {
                return unit[this.replaceDict[match]] || '';
            });
            this.returnArrayTemplate.forEach(item => {
                let returnValue = item.field;
                returnDataArray.push({
                    name: item.name,
                    value: returnValue.replace(regex, (match) => {
                        return unit[this.replaceDict[match]] || '';
                    })
                })
            })
            this.$emit('select', returnDataArray, unit.enterpriseType);

            // 标识这是选择操作
            this.internalIsSelected = true;
            this.$emit('update:isSelected', this.internalIsSelected);
            this.displayValue = displayValue;
            this.showModal = false;
        },
        getTableData() {
            request.get("/place/findPage", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    param: this.search,
                    typeId: this.typeId
                }
            }).then(res => {
                if (res.code == '200') {
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                }
            })
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getTableData();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.getTableData();
        },
        cleanModal() {
            this.showModal = false;
        },
        // 显示提示框
        showTooltip(e) {
            const tooltip = document.getElementById('tooltip');

            if (tooltip) {
                // 设置位置
                tooltip.style.left = `${e.clientX + 10}px`;
                tooltip.style.top = `${e.clientY + 10}px`;

                // 触发过渡动画
                setTimeout(() => {
                    tooltip.classList.add('show');
                }, 10);
            }
        },
        // 隐藏提示框
        hideTooltip() {
            const tooltip = document.getElementById('tooltip');
            if (tooltip) {
                tooltip.classList.remove('show');
            }
        }

    },
}
</script>

<style scoped>
.privy-input-style {
    border: none;
    height: 6mm;
    padding: 0;
    border-bottom: 1px solid black;
    outline: none;
    text-align: center;
    font-size: 5mm;
    font-family: 仿宋;
}

.overlay-layer {
    display: inline;
}

.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}

:deep(.privyInfoTable th),
:deep(.privyInfoTable td) {
    border: 1px solid #ebeef5 !important;
}

/* 提示框样式 */
.tooltip {
    position: fixed;
    background-color: rgba(94, 93, 93, 0.7);
    color: rgb(255, 255, 255);
    padding: 5px 10px;
    border-radius: 4px;
    width: 150px;
    height: 20px;
    font-size: 14px;
    pointer-events: none;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: '仿宋';

    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease;
}

/* 显示状态 */
#tooltip.show {
    opacity: 1;
    visibility: visible;
}
</style>
